<?php

namespace app\common\model;
use \think\Cookie;
use \think\Db;
use think\Session;

/**
 * 第三方登录
 */
class Thirdlogin extends Base{
	/****万能钥匙登录******/
	public function wifilogin($token) {
		import('wifilogin.wifi', EXTEND_PATH);
		$wifi = new \Wifi($token);
		$getAccessToken = $wifi->getAccessToken();
		$UserInfo = $wifi->qryOidUserInfo($getAccessToken['accessToken'],$getAccessToken['oid']);
		//授权登陆后获取的开放Id 是否已经注册
		$userapi = db('MemberUserapi')->where(array("wifiid"=>$UserInfo['oid']))->find();
		$backurl ="/";
		if($userapi){
			//直接登录
			$user = model('User');
			$user->autoLogin(array('uid'=>$userapi['uid']));
			header('Location:'.$backurl);
			exit();
		}else{
			//获取最新键
			$row = Db::query('SHOW TABLE STATUS WHERE name = "cps_member"');
			$uid = $UserInfo['nickName']?$UserInfo['nickName']:"漫友".intval($row[0]['Auto_increment']);
			$data['uid'] = $row[0]['Auto_increment'];
			$data['wifiid'] = $UserInfo['oid'];
			db('MemberUserapi')->insert($data);
			//开始注册新用户并登录
			$avatar = null;
			if($UserInfo['minHeadImgUrl']){	
				$dir  = setavatardir($row[0]['Auto_increment']);
				$file = BASE_PATH . '/uploads/avatar/' . $dir;
				$filename='avatar_middle.png';
				file_get_img($UserInfo['minHeadImgUrl'],$file,true,$filename);
				$avatar = '/uploads/avatar/' . $dir.$filename;
			}
			$this->register($uid,$email = '',$backurl,$avatar);
		}
		
	}

	public function register($username = '',$email = '',$backurl,$avatar){
		$repassword = $password = md5($username);
		$email = generate_password(rand(6,10))."@qq.com";
		$user = model('User');		
		$result = $user->register($username, $password, $repassword, $email,true,$avatar);
		if ($result) {
			header('Location:'.$backurl);
		}
		exit();
	}

}

?>